- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path1122. Relative Sort Array.go
48 lines (45 loc) · 892 Bytes
/
1122. Relative Sort Array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package leetcode
import"sort"
// 解法一 桶排序,时间复杂度 O(n^2)
funcrelativeSortArray(A, B []int) []int {
count:= [1001]int{}
for_, a:=rangeA {
count[a]++
}
res:=make([]int, 0, len(A))
for_, b:=rangeB {
forcount[b] >0 {
res=append(res, b)
count[b]--
}
}
fori:=0; i<1001; i++ {
forcount[i] >0 {
res=append(res, i)
count[i]--
}
}
returnres
}
// 解法二 模拟,时间复杂度 O(n^2)
funcrelativeSortArray1(arr1 []int, arr2 []int) []int {
leftover, m, res:= []int{}, make(map[int]int), []int{}
for_, v:=rangearr1 {
m[v]++
}
for_, s:=rangearr2 {
count:=m[s]
fori:=0; i<count; i++ {
res=append(res, s)
}
m[s] =0
}
forv, count:=rangem {
fori:=0; i<count; i++ {
leftover=append(leftover, v)
}
}
sort.Ints(leftover)
res=append(res, leftover...)
returnres
}